package ecom.shell.commandsImpl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.StringTokenizer;
import shell.Shell;
import shell.ShellCommand;
import shell.ShellContext;

public class BatchCommands implements ShellCommand {

    private ShellContext _context = null;

    public BatchCommands(ShellContext context) {
        _context = context;
    }

    @Override
    public String getName() {
        return "batch";
    }

    @Override
    public String getUsage() {
        return "batch [-stopOnError] filename";
    }

    @Override
    public String getShortDescription() {
        return "run commands\n";
    }

    @Override
    public String execute(String cmdline, PrintStream out, PrintStream err) throws Exception {
        Shell shell = (Shell) _context.getVar("shellMaster");
        StringTokenizer cmdLine = new StringTokenizer(cmdline, " ");
        String filePath = "";
        String cmd = "";
        boolean stopOnError;
        InputStream in = null;

        cmdLine.nextToken();

        int sleep = Integer.parseInt(cmdLine.nextToken());

        if (cmdLine.countTokens() == 1) {
            out.println("  [stopOnError = FALSE]");
            stopOnError = false;
        } else if (cmdLine.countTokens() == 2) {
            cmdLine.nextToken();
            out.println("  [stopOnError = TRUE]");
            stopOnError = true;
        } else {
            err.println(EcomCommandsConstantes.INCORRECT_NUMBER_ARGS);
            return "";
        }
        filePath = cmdLine.nextToken();

        try {
            in = new FileInputStream(filePath);

            InputStreamReader inReader = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(inReader);

            while ((cmd = br.readLine()) != null) {
                out.println("\n  [BATCH command] -> " + cmd + "\n");
                try {
                    out.println(shell.executeCommand(cmd, out, err));
                } catch (Exception ex) {
                    if (stopOnError == true) {
                        err.println("Error and stopOnError ON : stop batch execution");
                        err.println(ex);
                        return "";
                    } else {
                        err.println("Shell :" + ex);
                    }
                }
            }
            br.close();
        } catch (FileNotFoundException e) {
            err.println("File \"" + filePath + "\" not found" + e);
        } catch (IOException e) {
            err.println("Error : " + e);
        }
        return "";
    }
}